package com.koron.css2.common.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.swan.excel.Excel;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ImportUtils {
	
	private static Logger log = LogManager.getLogger(ImportUtils.class);
	
	public static HttpEntity<?> importExcel(List<?> data, String fileName, String fileTemplate, String btlTemplate){
		URL url = ImportUtils.class.getClassLoader().getResource(fileTemplate);
		if(url == null) {
			log.error("类路径下不存在{}文件", fileTemplate);
			throw new NullPointerException("类路径下不存在" + fileTemplate + "文件");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", data);
		return Excel.createFile(fileName, new File(url.getPath()), btlTemplate, map);
	}
	
	public static HttpEntity<?> importTxt(List<?> data, String title, String filename){
		try {
			Objects.requireNonNull(title, "导出的标题不能为空");
			Objects.requireNonNull(filename, "文件名不能为空");
			String line = System.getProperty("line.separator");
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			out.write(title.getBytes());
			out.write(line.getBytes());
			for(Object str : data) {
				out.write(Objects.toString(str, "null").getBytes("UTF-8"));
				out.write(line.getBytes());
			}
			HttpHeaders header = new HttpHeaders();
			String fn = URLEncoder.encode(filename, "UTF-8"); // new String(fileName.getBytes(),"ISO8859-1");
			header.add("Content-Disposition", "attachment ; filename=" + fn + ".txt");
			header.add("Content-Type", "text/plain");
			return new ResponseEntity<byte[]>(out.toByteArray(), header, HttpStatus.OK);
		}catch(Exception ex) {
			log.error("导出 txt 文件失败" + ex);
			return new ResponseEntity<String>("导出 txt 文件失败", HttpStatus.OK);
		}
	}

}
